<script setup lang="ts">
import {onMounted, ref} from 'vue';
import request from '../plugins/request.js'
import {showFailToast, showSuccessToast} from "vant";
import qs from 'qs'
import UserCard from "../components/UserCard.vue";
import {getCurrentUser} from "../service/user";

const userList = ref([])
const matchUserList = ref([])
const loading = ref(false)

const matchUser = async () => {
  const user = await getCurrentUser()
  loading.value = true
  const num = 10
  const result = await request.get(`/user/list/match/${num}`, {
    paramsSerializer: params => {
      return qs.stringify(params, {indices: false})
    }
  })
  const {code, data} = result
  if (code === 200 && data) {
    data.forEach(item => {
      if (item.tags) {
        item.tags = JSON.parse(item.tags)
      }
    })
    matchUserList.value = data
    loading.value = false
  } else {
    loading.value = false
    // showFailToast('获取推荐用户失败')
  }
}

const recommend = async () => {
  loading.value = true
  // 发送数据请求
  const userListData = await request.get('/user/recommend', {
    params: {
      pageSize: 20,
      pageNum: 1
    },
    paramsSerializer: params => {
      return qs.stringify(params, {indices: false})
    }
  }).then((response) => {
    return response?.data?.records;
    loading.value = false
  }).catch(() => {
    showFailToast('用户刷新失败');
    loading.value = false
  })
  if (userListData) {
    userListData.forEach(item => {
      if (item.tags) {
        item.tags = JSON.parse(item.tags)
      }
    })
    userList.value = userListData;
    loading.value = false
  }
}

onMounted(async () => {
  await recommend()
})

const activeName = ref('a')

const beforeChange = (index) => {
  // 返回 false 表示阻止此次切换
  // if (index === 'a') {
  //   console.log(111)
  //   return false;
  // }

  // 返回 Promise 来执行异步逻辑
  return new Promise(async (resolve) => {
    // 在 resolve 函数中返回 true 或 false
    if (activeName.value === 'a') {
      await matchUser()
    } else {
      await recommend()
    }
    resolve(true);
  });
};
</script>

<template>
    <div v-show="loading" class="wrapper" @click.stop>
        <van-loading class="block" color="#0094ff" v-show="loading">加载中</van-loading>
    </div>

  <van-tabs v-model:active="activeName" :before-change="beforeChange">
    <van-tab title="普通用户" name="a">
      <user-card v-if="userList.length>0" :user-list="userList"></user-card>
      <van-empty v-else description="暂无信息"/>
    </van-tab>
    <van-tab title="推荐用户" name="b">
      <user-card v-if="matchUserList.length>0" :user-list="matchUserList"></user-card>
      <van-empty v-else description="暂无信息"/>
    </van-tab>
  </van-tabs>


</template>

<style scoped>
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
}
</style>